import React, { useState, useMemo } from 'react';
import { MCmd, MUser, obj_int, loc, obj_str, no_del, PanelFind, filter_row, useCmd, useHigh, Btn, GridTable } from 'sui';
import { DlgVal } from '../type/ctl';
import { BindUser } from './user';
import { Auth } from './auth';
import { useAccess } from 'cache';

const AuthView = () => {
    const [open_val, openVal] = useState(false);
    const [high] = useHigh(140, 100);
    const [no_acc] = useAccess();
    const umd = useCmd("auth/list", null, {count: true});

    const getRow = useMemo(() => {
        const lst = ["sn", "name"];
        return filter_row(umd.value, lst, umd.filter);
    }, [umd.value, umd.filter]);

    const act = {
        "add": v => umd.update("auth/add", {"v": v}, () => umd.hreturn()),
        "edit": v => umd.update("auth/md", {"v": [v]}, () => umd.hreturn()),
    };

    const pact = {
        "add": v => openVal(true),
        "edit": v => openVal(true),
    };

    if (umd.isFin("user")) {
        const hreturn = () => {
            umd.reload();
            umd.hreturn();
        };

        return <BindUser hreturn={hreturn} cur={umd.cur}/>;
    }

    if (umd.isFin("auth")) {
        return <Auth hreturn={umd.hreturn} cur={umd.cur}/>;
    }

    const hDel = (val) => {
        if (no_del()) {
            return;
        }

        umd.update("auth/rm", {"k": obj_str(val, "sn")});
    };

    const col = [
        {name: loc("l_193"), key: 'index', width: 70, frozen: true},
        {name: loc("l_238"), key: 'e_opt', width: 220, frozen: true, formatter: (props) => {
            const d = props.row;
            return (
                <div className="inline-flex">
                    <MCmd hcmd={() => umd.pact(pact, d, "edit")} itype="edit" disabled={no_acc("ke")}/>
                    <MCmd hcmd={() => hDel(d)} itype="del" disabled={no_acc("ke")}/>
                    <MCmd hcmd={() => umd.pact(null, d, "auth")} itype="bom" title={loc("l_118")} disabled={no_acc("ke")}/>
                    <MUser hcmd={() => umd.pact(null, d, "user")} title={loc("l_254")} num={obj_int(d, "user_num")} disabled={no_acc("ke")}/>
                </div>
            );
        }},
        {name: loc("l_495"), key: 'sn', width: 200},
        {name: loc("l_228"), key: 'name', width: 200},
    ];

    const Right = () => (
        <div className="inline-flex">
            <Btn hcmd={() => umd.pact(pact, null, "add")} className="ml-3" disabled={no_acc("ke")}>{loc("l_239")}</Btn>
        </div>
    );

    return (
        <div className="flex flex-col">
            <PanelFind left={loc("l_258")} right={<Right/>} hcmd={umd.setFilter}/>
            <GridTable high={high} col={col} row={getRow} rowHeight={48}/>
            <DlgVal open={open_val} hcmd={v => umd.act(act, v)} setOpen={openVal} data={umd.cur} main={umd.value}/>
        </div>
    );
};

export {AuthView};
